﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.Azure;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models.ViewModel.News;
using ELearning.Common;
using ELearning.Common.Http;
using ELearning.Models;
using ELearning.Models.ViewModel.Project;
using RestSharp;
using static Microsoft.Graph.CoreConstants;

namespace ELearning.API.Controllers.AdminControllers
{
    /// <summary>
    /// 项目相关功能
    /// </summary>
    public class ProjectController : BaseApiController
    {
        /// <summary>
        /// 项目操作service
        /// </summary>
        private EProjectService ProjectService => new EProjectService();

        /// <summary>
        /// 项目与角色关联操作service
        /// </summary>
        private RProjectRoleService rProjectRoleService => new RProjectRoleService();

        /// <summary>
        /// 项目与附件关联操作service
        /// </summary>
        private RProjectAttaService RProjectAttaService => new RProjectAttaService();

        /// <summary>
        /// 附件操作service
        /// </summary>
        private EAttachmentService EAttachmentService => new EAttachmentService();

        /// <summary>
        /// 角色用户管理操作service
        /// </summary>
        private RRoleUserService RRoleUserService => new RRoleUserService();

        /// <summary>
        /// 获取项目列表
        /// </summary>
        [HttpPost, Route("api/eproject/GetProjectList")]
        public ServiceResponse<ProjectViewModel> GetProjectList(ProjectRequest request)
        {
            Expression<Func<EProject, bool>> whereLamdba = u => !u.IsDelete;
            if (!string.IsNullOrEmpty(request.Title))
                whereLamdba = whereLamdba.And(p => p.Title.Contains(request.Title));
            var models = ProjectService.FindPageList(request.Page, request.PageSize, out var total, request.OrderBy, request.SortDir, whereLamdba).ToList();
            var viewModel = new ProjectViewModel { TotalCount = total };
            var ids = models.Select(p => p.ID).ToList();
            var rprs = rProjectRoleService.FindList(r => ids.Contains(r.ProjectId)).ToList();
            foreach (var project in models)
            {
                var v = project.MapTo<ProjectItem, EProject>();
                v.CreateTime = project.CreateTime.ToString("yyyy-MM-dd HH:mm");
                v.RoleIdList = rprs.Where(r => r.ProjectId == project.ID).Select(r => r.RoleId).ToList();
                viewModel.Items.Add(v);
            }

            return ServiceResponse<ProjectViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 获取全部的项目列表
        /// </summary>
        [HttpGet, Route("api/eproject/GetAllProjectList")]
        public ServiceResponse<List<ProjectOptionItem>> GetAllProjectList()
        {
            var userId = CurrentUserModel?.UserId ?? Guid.Empty;
            var roleIds = RRoleUserService.FindList(r => r.UserID == userId).Select(r => r.RoleID).ToList();
            var projectIds = rProjectRoleService.FindList(r => roleIds.Contains(r.RoleId)).Select(r => r.ProjectId).ToList();
            var models = ProjectService.FindList(p => !p.IsDelete && projectIds.Contains(p.ID)).ToList();
            var viewModels = new List<ProjectOptionItem>();
            foreach (var project in models)
            {
                var v = new ProjectOptionItem
                {
                    ID = project.ID,
                    Title = project.Title
                };
                viewModels.Add(v);
            }

            return ServiceResponse<List<ProjectOptionItem>>.SuccessResponse(CommonConst.OprateSuccessStr, viewModels);
        }

        /// <summary>
        /// 添加项目
        /// </summary>
        [HttpPost, Route("api/eproject/AddModel")]
        public ServiceResponse<bool> AddModel(ProjectItem viewModel)
        {
            var model = new EProject
            {
                ID = GuidUtil.NewSequentialId(),
                Creater = CurrentUserModel?.LoginName ?? string.Empty,
                CreateTime = DateTime.Now,
                IsDelete = false,
                ModifyTime = DateTime.Now,
                Modifyer = CurrentUserModel?.LoginName ?? string.Empty,
                Note = viewModel.Note,
                Title = viewModel.Title
            };

            if (viewModel.RoleIdList != null && viewModel.RoleIdList.Any())
            {
                foreach (var roleId in viewModel.RoleIdList)
                {
                    rProjectRoleService.AddNoSaveChange(new RProjectRole
                    {
                        Creater = CurrentUserModel?.LoginName ?? string.Empty,
                        CreateTime = DateTime.Now,
                        ID = GuidUtil.NewSequentialId(),
                        ProjectId = model.ID,
                        RoleId = roleId
                    });
                }
            }

            ProjectService.Add(model);
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        [HttpPost, Route("api/eproject/UpdateModel")]
        public ServiceResponse<bool> UpdateModel(ProjectItem viewModel)
        {
            var model = ProjectService.Find(p => !p.IsDelete && p.ID == viewModel.ID);
            if (model != null)
            {
                model.ModifyTime = DateTime.Now;
                model.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
                model.Title = viewModel.Title;
                model.Note = viewModel.Note;

                var deleteList = rProjectRoleService.FindList(r => r.ProjectId == model.ID).ToList();
                rProjectRoleService.DeletesNoSaveChange(deleteList);

                if (viewModel.RoleIdList != null && viewModel.RoleIdList.Any())
                {
                    foreach (var roleId in viewModel.RoleIdList)
                    {
                        rProjectRoleService.AddNoSaveChange(new RProjectRole
                        {
                            Creater = CurrentUserModel?.LoginName ?? string.Empty,
                            CreateTime = DateTime.Now,
                            ID = GuidUtil.NewSequentialId(),
                            ProjectId = model.ID,
                            RoleId = roleId
                        });
                    }
                }

                ProjectService.Update(model);
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="id">项目id</param>
        [HttpPost, Route("api/eproject/DeleteModel")]
        public ServiceResponse<bool> DeleteModel(Guid id)
        {
            var model = ProjectService.Find(p => !p.IsDelete && p.ID == id);
            if (model != null)
            {
                var deleteList = rProjectRoleService.FindList(r => r.ProjectId == id).ToList();
                rProjectRoleService.DeletesNoSaveChange(deleteList);

                model.IsDelete = true;
                ProjectService.Update(model);
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 获取项目下面的上传资料列表
        /// </summary>
        [HttpPost, Route("api/eproject/GetDataList")]
        public ServiceResponse<GetDataListViewModel> GetDataList(DataListRequest request)
        {
            Expression<Func<RProjectAtta, bool>> whereLamdba = r => r.ProjectId == request.ProjectId;
            var rpes = RProjectAttaService.FindPageList(request.Page, request.PageSize, out var total, request.OrderBy, request.SortDir, whereLamdba).ToList();
            var attaids = rpes.Select(r => r.AttaId).ToList();
            var models = EAttachmentService.FindList(e => attaids.Contains(e.ID)).ToList();
            var projectName = ProjectService.Find(p => p.ID == request.ProjectId)?.Title ?? string.Empty;
            var viewModel = new GetDataListViewModel { TotalCount = total };
            foreach (var model in models)
            {
                var v = model.MapTo<DataListItem, EAttachment>();
                v.TeachingID = request.ProjectId;
                v.ProjectName = projectName;
                v.CreateTime = model.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                v.ModifyTime = model.ModifyTime.ToString("yyyy-MM-dd HH:mm:ss");
                viewModel.Items.Add(v);
            }

            return ServiceResponse<GetDataListViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 上传资料
        /// </summary>
        [HttpPost, Route("api/eproject/AddData")]
        public ServiceResponse<bool> AddData(DataListItem viewModel)
        {
            var model = viewModel.MapTo<EAttachment, DataListItem>();
            model.ID = GuidUtil.NewSequentialId();
            model.Creater = CurrentUserModel?.LoginName ?? string.Empty;
            model.CreateTime = DateTime.Now;
            model.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
            model.ModifyTime = DateTime.Now;

            //关联关系
            var rpe = new RProjectAtta
            {
                ID = GuidUtil.NewSequentialId(),
                AttaId = model.ID,
                Creater = CurrentUserModel?.LoginName ?? string.Empty,
                CreateTime = DateTime.Now,
                ProjectId = model.TeachingID
            };
            RProjectAttaService.AddNoSaveChange(rpe);

            EAttachmentService.Add(model);
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 更新资料
        /// </summary>
        [HttpPost, Route("api/eproject/UpdateData")]
        public ServiceResponse<bool> UpdateData(DataListItem viewModel)
        {
            var model = EAttachmentService.Find(e => e.ID == viewModel.ID);
            if (model != null)
            {
                model.AttachmentDIsplayName = viewModel.AttachmentDIsplayName;
                model.AttachmentExt = viewModel.AttachmentExt;
                model.AttachmentName = viewModel.AttachmentName;
                model.Duration = viewModel.Duration;
                model.AttachmentSize = viewModel.AttachmentSize;
                model.AttachmentUrl = viewModel.AttachmentUrl;
                model.DownloadUrl = viewModel.DownloadUrl;
                model.Description = viewModel.Description;
                model.SortNum = viewModel.SortNum;

                model.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
                model.ModifyTime = DateTime.Now;
                EAttachmentService.Update(model);
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除资料
        /// </summary>
        [HttpGet, Route("api/eproject/DeleteData")]
        public ServiceResponse<bool> DeleteData(Guid id, Guid projectId)
        {
            var rpe = RProjectAttaService.Find(r => r.ProjectId == projectId && r.AttaId == id);
            if (rpe != null)
            {
                RProjectAttaService.Delete(rpe);
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }
    }
}